package com.caochenlei.codebuilder.config;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.caochenlei.codebuilder.utils.SystemUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DatabasesConfigUtil {
	private static Logger logger = LoggerFactory.getLogger(DatabasesConfigUtil.class);

	/**
	 * 功能说明：读取配置文件
	 * 
	 * @param configName
	 * @return
	 */
	public static Map<String, Map<String, String>> read(String configName) {
		try {
			SAXReader saxReader = new SAXReader();
			Document document = null;
			try {
				document = saxReader.read(new BufferedReader(new InputStreamReader(new FileInputStream(SystemUtil.getConfigAbsolutePathByName(configName)), "UTF-8")));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			Element rootElement = document.getRootElement();

			logger.info("读取配置文件配置：" + configName);
			logger.info("读取配置文件路径：" + SystemUtil.getConfigAbsolutePathByName(configName));

			Map<String, Map<String, String>> map = new TreeMap<String, Map<String, String>>(new Comparator<String>() {
				@Override
				public int compare(String obj1, String obj2) {
					return obj1.compareTo(obj2);
				}
			});

			List<?> elements = rootElement.elements();
			for (int i = 0; i < elements.size(); i++) {
				Element element = (Element) elements.get(i);
				logger.info("读取配置文件父参数：" + element.attributeValue("name"));

				Map<String, String> m = new TreeMap<String, String>(new Comparator<String>() {
					@Override
					public int compare(String obj1, String obj2) {
						return obj1.compareTo(obj2);
					}
				});

				List<?> propertys = element.elements();
				for (int j = 0; j < propertys.size(); j++) {
					Element property = (Element) propertys.get(j);

					m.put(property.attributeValue("name"), property.getTextTrim());
					map.put(element.attributeValue("name"), m);
				}

				logger.info("读取配置文件子参数：" + m.toString());
			}

			return map;
		} catch (DocumentException e) {
			logger.error("读取配置文件失败：" + e.getMessage());
		}
		return null;
	}

	/**
	 * 功能说明：替换dbUrl基本参数
	 * 
	 * @param dbUrl
	 * @param dbIp
	 * @param dbPort
	 * @param dbName
	 * @return
	 */
	public static String replaceUrlConfig(String dbUrl, String dbIp, String dbPort, String dbName) {
		return dbUrl.replace("[dbIp]", dbIp).replace("[dbPort]", dbPort).replace("[dbName]", dbName);
	}

}
